package com.xhlj.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xhlj.entity.UserInfo;
import com.xhlj.mapper.UserInfoMapper;
import com.xhlj.service.UserInfoService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.UserDetailsManager;

import java.util.ArrayList;
import java.util.List;

public class DbUserDetailsManager implements UserDetailsManager, UserDetailsPasswordService {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Resource
    UserInfoMapper userInfoMapper;

    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        return null;
    }

    @Override
    public void createUser(UserDetails user) {
        String password = passwordEncoder.encode(user.getPassword());
        UserInfo userInfo = new UserInfo();
        userInfo.setUserPhone(user.getUsername());
        userInfo.setUserPassword(password);
        userInfoService.save(userInfo);
    }

    @Override
    public void updateUser(UserDetails user) {

    }

    @Override
    public void deleteUser(String username) {

    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {

    }

    @Override
    public boolean userExists(String username) {
        return false;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper();
        wrapper.eq(UserInfo::getUserPhone, username);
        UserInfo user = userInfoService.getOne(wrapper);
        if (user == null) {

            throw new UsernameNotFoundException("手机号不存在");
        }
//        权限直接不管了
        List<GrantedAuthority> authorities = new ArrayList<>();

        return new User(user.getUserPhone(), passwordEncoder.encode(user.getUserPassword()), authorities);

    }
}
